package com.wetool.controller;

import com.wetool.feign.UploadFeignClient;
import com.wetool.model.Base64Image;
import com.wetool.model.Result;
import com.wetool.model.UploadImageResult;
import com.wetool.model.UploadQRCodeDTO;
import com.wetool.push.api.model.PushMsgType;
import com.wetool.push.api.model.server.PushMessage;
import com.wetool.serialize.UploadQRCodeService;
import com.wetool.service.MessagePushService;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.ws.rs.QueryParam;

/**
 * Created by zhanbin on 17-6-29.
 * 微信扫码上传Controller
 */
@Api(description = "二维码扫码上传")
@RestController
public class QRCodeUploadController {
    private final static String QRCODE_ERROR = "二维码无效，请刷新二维码。";
    private final static int SUCCESS = 0;
    private final static int FAILED = 1;


    @Autowired
    private UploadFeignClient uploadFeignClient;

    @Autowired
    private UploadQRCodeService uploadQRCodeService;

    @Autowired
    private MessagePushService messagePushService;


    @ApiOperation(value = "二维码扫码上传", notes = "扫码上传跳转页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "timestamp", value = "二维码生成时间戳", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "token", value = "用户验证token", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "sn", value = "设备唯一标识", required = true, dataType = "String", paramType = "query")
    })
    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    public Object redirect(@QueryParam("sn") String sn, @QueryParam("timestamp") String timestamp, @QueryParam("token") String token) {
        //TODO 验证逻辑
        if (StringUtils.isEmpty(sn) || StringUtils.isEmpty(timestamp) || StringUtils.isEmpty(token)) {
            return QRCODE_ERROR + "参数不能为空。";
        }

        if (!(sn.length() == 14 || sn.length() == 12)) {
            return QRCODE_ERROR + "sn长度有误。";
        }

        //校验二维码有效性
        if (this.uploadQRCodeService.checkQRCodeValidity(timestamp)) {
            return QRCODE_ERROR + "已过期。";
        }

        return new ModelAndView("redirect:api/commodity-server/upload/index.html?sn=" + sn + "&timestamp=" + timestamp + "&token=" + token);
    }

    /**
     * 二维码扫码上传图片
     *
     * @param requestBody 包含Base64图片的DTO请求参数
     * @return 返回上传结果，成功返回0，失败返回1
     */
    @ApiOperation(value = "二维码扫码上传", notes = "二维码扫码上传图片并推送消息给二维码中指定的SN设备。单次调用接口。", consumes = "application/json", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "timestamp", value = "二维码生成时间戳", required = true, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "SN", value = "设备唯一标识", required = true, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "uploadKey", value = "上传图片文件", required = true, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "modType", value = "文件上传业务类型，决定文件存放路径", required = true, dataType = "String", paramType = "body", examples = @Example({@ExampleProperty("commodity"), @ExampleProperty("advert"), @ExampleProperty("test")})),
            @ApiImplicitParam(name = "file", value = "Base64文件", required = true, dataType = "String", paramType = "body"),
    })
    @PostMapping(value = "/uploadImageByScanQRCode")
    public ResponseEntity<?> uploadImageByScanQRCode(@RequestBody UploadQRCodeDTO requestBody) {

        //校验文件
        if (this.uploadQRCodeService.checkFileValidity(requestBody.getFile())) {
            return new ResponseEntity<>(new Result(FAILED, "上传文件内容损坏或格式有误。"), HttpStatus.OK);
        }

        //图片数据格式： data:image/png;base64,*****************
        // 其中********表示Base64加密后的内容，即：图片数据。

        String[] imgData = requestBody.getFile().split(","); //分割头和图片数据
        //String imgDataHead = imgData[0];//head 格式: data:image/<img type>;base64 例如: data:image/jpeg;base64
        String imgDataBase64 = imgData[1]; //base64 code

        //String imgType = imgDataHead.substring(5, imgDataHead.indexOf(";")); //获得图片类型

        //调用Upload 服务上传文件
        //并获取文件上传结果
        ResponseEntity<Result> resultResponseEntity = null;
        try {
            resultResponseEntity = this.uploadFeignClient.uploadImageBySimpleMethod(new Base64Image(imgDataBase64, requestBody.getModType(), requestBody.getUploadKey()));
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(new Result(FAILED, "文件上传失败"), HttpStatus.OK);
        }
        Result uploadResult = resultResponseEntity.getBody();

        if (uploadResult.getCode() == 0) {
            this.messagePushService.sendImageSyncMessage(new PushMessage<>(PushMsgType.QRCODE_IMAGE_SYNC, requestBody.getSN(), uploadResult.getUrl()));
            return new ResponseEntity<Object>(new Result(SUCCESS, "文件上传成功"), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(new Result(FAILED, "文件上传失败"), HttpStatus.OK);
        }
    }

    /**
     * 推送已经上传的图片信息到客户端
     */
    @PostMapping(value = "/pushImage")
    public ResponseEntity<?> pushImageToClient(@RequestBody UploadImageResult requestBody) {
        this.messagePushService.sendImageSyncMessage(new PushMessage<>(PushMsgType.QRCODE_IMAGE_SYNC, requestBody.getUploadKey(), requestBody.getSN()));
        return new ResponseEntity<Object>(true, HttpStatus.OK);
    }
}
